package com.shy.config.util;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.shy.config.common.JWTConstants;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JWTUtils {
    /**
     * 生成令牌
     *
     * @param object
     * @return
     */
    public static String createJWT(Object object) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("alg", "HS256");
        headers.put("typ", "JWT");
        return JWT.create()
                .withHeader(headers)
                .withClaim(JWTConstants.JWT_USER, JSONObject.toJSONString(object))
                .sign(Algorithm.HMAC256(JWTConstants.JWT_SECRET));
    }

    /**
     * 验证令牌
     */
    public static Boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(JWTConstants.JWT_SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解析令牌（获取数据）
     */
    public static String parseJWT(String token) {
        return JWT.decode(token).getClaim(JWTConstants.JWT_USER).asString();
    }
}
